IRCBot::Plugin.define "auth" do
	help_string false
	AUTH_USERS = ['niexs!eduardo','nix!eduardo','eduardo!eduardo','monkeyofdoom!ircuser']
	@authed_users = []
	PASSWORD = 'xyzzy' # Please change this if you're using it yourself
	class AuthedUser
		attr_reader :hostmask
		def initialize(hostmask,login_time=Time.new)
			@hostmask		= hostmask.downcase
			@login_time		= Time.new
			@last_active	= Time.new
			@stale			= false
		end
		
		def update_activity(time=Time.new)
			@last_active = time
		end
		
		def stale?()
			if Time.new - @last_active >= 180 then
				@stale = true
				return true
			else
				@stale = false
				return false
			end
		end
	end
	
	def command(user,target,message,hostmask)
		hostmask = hostmask.downcase
		
		logged = false
		for authed_user in @authed_users
			if authed_user.hostmask == hostmask then
				logged = true
			end
		end
		
		if logged then
			send('NOTICE '+user+' :Already logged in.')
		else
			puts PASSWORD
			if message.strip == PASSWORD and AUTH_USERS.include?(hostmask.split('@')[0]) then
				instance = AuthedUser.new(hostmask)
				@authed_users.push instance
				send("NOTICE #{user} :Logged in.")
			else
				send("NOTICE #{user} :*garbled* #{2.chr}UNAUTHORIZED PERSONNEL#{2.chr} *garbled*")
			end
		end
	end
	
	def prune_stale_users()
		for user in @authed_users
			if user.stale? then
				@authed_users.delete user
				send("NOTICE #{user.hostmask.split('!')[0]} :You've been logged out for inactivity.")
				
			end
		end
	end
	
	def privmsg_function(*args) # Terrible practice?
		prune_stale_users()
	end
	
	def is_auth_user?(hostmask)
		hostmask = hostmask.downcase
		prune_stale_users()
		
		authed = false
		for user in @authed_users
			if user.hostmask == hostmask then
				authed = true
				user.update_activity
			end
		end
		send("NOTICE #{hostmask.split('!')[0]} :You're not authorized!") if !authed
		return authed
	end
	
	def loop_hook()
		prune_stale_users()
	end
end
